home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.1.5 / modules / DownloadUtils.jsm < prev    next >
Text File  |  2009-11-08  |  17KB  |  503 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Download Manager Utility Code.
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Edward Lee <edward.lee@engineering.uiuc.edu>.
  18.  * Portions created by the Initial Developer are Copyright (C) 2008
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *
  23.  * Alternatively, the contents of this file may be used under the terms of
  24.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  25.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  26.  * in which case the provisions of the GPL or the LGPL are applicable instead
  27.  * of those above. If you wish to allow use of your version of this file only
  28.  * under the terms of either the GPL or the LGPL, and not to allow others to
  29.  * use your version of this file under the terms of the MPL, indicate your
  30.  * decision by deleting the provisions above and replace them with the notice
  31.  * and other provisions required by the GPL or the LGPL. If you do not delete
  32.  * the provisions above, a recipient may use your version of this file under
  33.  * the terms of any one of the MPL, the GPL or the LGPL.
  34.  *
  35.  * ***** END LICENSE BLOCK ***** */
  36.  
  37. var EXPORTED_SYMBOLS = [ "DownloadUtils" ];
  38.  
  39. /**
  40.  * This module provides the DownloadUtils object which contains useful methods
  41.  * for downloads such as displaying file sizes, transfer times, and download
  42.  * locations.
  43.  *
  44.  * List of methods:
  45.  *
  46.  * [string status, double newLast]
  47.  * getDownloadStatus(int aCurrBytes, [optional] int aMaxBytes,
  48.  *                   [optional] double aSpeed, [optional] double aLastSec)
  49.  *
  50.  * string progress
  51.  * getTransferTotal(int aCurrBytes, [optional] int aMaxBytes)
  52.  *
  53.  * [string timeLeft, double newLast]
  54.  * getTimeLeft(double aSeconds, [optional] double aLastSec)
  55.  *
  56.  * [string displayHost, string fullHost]
  57.  * getURIHost(string aURIString)
  58.  *
  59.  * [double convertedBytes, string units]
  60.  * convertByteUnits(int aBytes)
  61.  *
  62.  * [int time, string units, int subTime, string subUnits]
  63.  * convertTimeUnits(double aSecs)
  64.  */
  65.  
  66. const Cc = Components.classes;
  67. const Ci = Components.interfaces;
  68. const Cu = Components.utils;
  69. Cu.import("resource://gre/modules/PluralForm.jsm");
  70.  
  71. const kDownloadProperties =
  72.   "chrome://mozapps/locale/downloads/downloads.properties";
  73.  
  74. // These strings will be converted to the corresponding ones from the string
  75. // bundle on use
  76. let kStrings = {
  77.   statusFormat: "statusFormat2",
  78.   transferSameUnits: "transferSameUnits",
  79.   transferDiffUnits: "transferDiffUnits",
  80.   transferNoTotal: "transferNoTotal",
  81.   timePair: "timePair",
  82.   timeLeftSingle: "timeLeftSingle",
  83.   timeLeftDouble: "timeLeftDouble",
  84.   timeFewSeconds: "timeFewSeconds",
  85.   timeUnknown: "timeUnknown",
  86.   doneScheme: "doneScheme",
  87.   doneFileScheme: "doneFileScheme",
  88.   units: ["bytes", "kilobyte", "megabyte", "gigabyte"],
  89.   // Update timeSize in convertTimeUnits if changing the length of this array
  90.   timeUnits: ["seconds", "minutes", "hours", "days"],
  91. };
  92.  
  93. // This object will lazily load the strings defined in kStrings
  94. let gStr = {
  95.   /**
  96.    * Initialize lazy string getters
  97.    */
  98.   _init: function()
  99.   {
  100.     // Make each "name" a lazy-loading string that knows how to load itself. We
  101.     // need to locally scope name and value to keep them around for the getter.
  102.     for (let [name, value] in Iterator(kStrings))
  103.       let ([n, v] = [name, value])
  104.         gStr.__defineGetter__(n, function() gStr._getStr(n, v));
  105.   },
  106.  
  107.   /**
  108.    * Convert strings to those in the string bundle. This lazily loads the
  109.    * string bundle *once* only when used the first time.
  110.    */
  111.   get _getStr()
  112.   {
  113.     // Delete the getter to be overwritten
  114.     delete gStr._getStr;
  115.  
  116.     // Lazily load the bundle into the closure on first call to _getStr
  117.     let getStr = Cc["@mozilla.org/intl/stringbundle;1"].
  118.                  getService(Ci.nsIStringBundleService).
  119.                  createBundle(kDownloadProperties).
  120.                  GetStringFromName;
  121.  
  122.     // _getStr is a function that sets string "name" to stringbundle's "value"
  123.     return gStr._getStr = function(name, value) {
  124.       // Delete the getter to be overwritten
  125.       delete gStr[name];
  126.  
  127.       try {
  128.         // "name" is a string or array of the stringbundle-loaded "value"
  129.         return gStr[name] = typeof value == "string" ?
  130.                             getStr(value) :
  131.                             value.map(getStr);
  132.       } catch (e) {
  133.         log(["Couldn't get string '", name, "' from property '", value, "'"]);
  134.         // Don't return anything (undefined), and because we deleted ourselves,
  135.         // future accesses will also be undefined
  136.       }
  137.     };
  138.   },
  139. };
  140. // Initialize the lazy string getters!
  141. gStr._init();
  142.  
  143. // Keep track of at most this many second/lastSec pairs so that multiple calls
  144. // to getTimeLeft produce the same time left
  145. const kCachedLastMaxSize = 10;
  146. let gCachedLast = [];
  147.  
  148. let DownloadUtils = {
  149.   /**
  150.    * Generate a full status string for a download given its current progress,
  151.    * total size, speed, last time remaining
  152.    *
  153.    * @param aCurrBytes
  154.    *        Number of bytes transferred so far
  155.    * @param [optional] aMaxBytes
  156.    *        Total number of bytes or -1 for unknown
  157.    * @param [optional] aSpeed
  158.    *        Current transfer rate in bytes/sec or -1 for unknown
  159.    * @param [optional] aLastSec
  160.    *        Last time remaining in seconds or Infinity for unknown
  161.    * @return A pair: [download status text, new value of "last seconds"]
  162.    */
  163.   getDownloadStatus: function DU_getDownloadStatus(aCurrBytes, aMaxBytes,
  164.                                                    aSpeed, aLastSec)
  165.   {
  166.     if (aMaxBytes == null)
  167.       aMaxBytes = -1;
  168.     if (aSpeed == null)
  169.       aSpeed = -1;
  170.     if (aLastSec == null)
  171.       aLastSec = Infinity;
  172.  
  173.     // Calculate the time remaining if we have valid values
  174.     let seconds = (aSpeed > 0) && (aMaxBytes > 0) ?
  175.       (aMaxBytes - aCurrBytes) / aSpeed : -1;
  176.  
  177.     // Update the bytes transferred and bytes total
  178.     let status;
  179.     let (transfer = DownloadUtils.getTransferTotal(aCurrBytes, aMaxBytes)) {
  180.       // Insert 1 is the download progress
  181.       status = replaceInsert(gStr.statusFormat, 1, transfer);
  182.     }
  183.  
  184.     // Update the download rate
  185.     let ([rate, unit] = DownloadUtils.convertByteUnits(aSpeed)) {
  186.       // Insert 2 is the download rate
  187.       status = replaceInsert(status, 2, rate);
  188.       // Insert 3 is the |unit|/sec
  189.       status = replaceInsert(status, 3, unit);
  190.     }
  191.  
  192.     // Update time remaining
  193.     let ([timeLeft, newLast] = DownloadUtils.getTimeLeft(seconds, aLastSec)) {
  194.       // Insert 4 is the time remaining
  195.       status = replaceInsert(status, 4, timeLeft);
  196.  
  197.       return [status, newLast];
  198.     }
  199.   },
  200.  
  201.   /**
  202.    * Generate the transfer progress string to show the current and total byte
  203.    * size. Byte units will be as large as possible and the same units for
  204.    * current and max will be supressed for the former.
  205.    *
  206.    * @param aCurrBytes
  207.    *        Number of bytes transferred so far
  208.    * @param [optional] aMaxBytes
  209.    *        Total number of bytes or -1 for unknown
  210.    * @return The transfer progress text
  211.    */
  212.   getTransferTotal: function DU_getTransferTotal(aCurrBytes, aMaxBytes)
  213.   {
  214.     if (aMaxBytes == null)
  215.       aMaxBytes = -1;
  216.  
  217.     let [progress, progressUnits] = DownloadUtils.convertByteUnits(aCurrBytes);
  218.     let [total, totalUnits] = DownloadUtils.convertByteUnits(aMaxBytes);
  219.  
  220.     // Figure out which byte progress string to display
  221.     let transfer;
  222.     if (total < 0)
  223.       transfer = gStr.transferNoTotal;
  224.     else if (progressUnits == totalUnits)
  225.       transfer = gStr.transferSameUnits;
  226.     else
  227.       transfer = gStr.transferDiffUnits;
  228.  
  229.     transfer = replaceInsert(transfer, 1, progress);
  230.     transfer = replaceInsert(transfer, 2, progressUnits);
  231.     transfer = replaceInsert(transfer, 3, total);
  232.     transfer = replaceInsert(transfer, 4, totalUnits);
  233.  
  234.     return transfer;
  235.   },
  236.  
  237.   /**
  238.    * Generate a "time left" string given an estimate on the time left and the
  239.    * last time. The extra time is used to give a better estimate on the time to
  240.    * show. Both the time values are doubles instead of integers to help get
  241.    * sub-second accuracy for current and future estimates.
  242.    *
  243.    * @param aSeconds
  244.    *        Current estimate on number of seconds left for the download
  245.    * @param [optional] aLastSec
  246.    *        Last time remaining in seconds or Infinity for unknown
  247.    * @return A pair: [time left text, new value of "last seconds"]
  248.    */
  249.   getTimeLeft: function DU_getTimeLeft(aSeconds, aLastSec)
  250.   {
  251.     if (aLastSec == null)
  252.       aLastSec = Infinity;
  253.  
  254.     if (aSeconds < 0)
  255.       return [gStr.timeUnknown, aLastSec];
  256.  
  257.     // Try to find a cached lastSec for the given second
  258.     aLastSec = gCachedLast.reduce(function(aResult, aItem)
  259.       aItem[0] == aSeconds ? aItem[1] : aResult, aLastSec);
  260.  
  261.     // Add the current second/lastSec pair unless we have too many
  262.     gCachedLast.push([aSeconds, aLastSec]);
  263.     if (gCachedLast.length > kCachedLastMaxSize)
  264.       gCachedLast.shift();
  265.  
  266.     // Apply smoothing only if the new time isn't a huge change -- e.g., if the
  267.     // new time is more than half the previous time; this is useful for
  268.     // downloads that start/resume slowly
  269.     if (aSeconds > aLastSec / 2) {
  270.       // Apply hysteresis to favor downward over upward swings
  271.       // 30% of down and 10% of up (exponential smoothing)
  272.       let (diff = aSeconds - aLastSec) {
  273.         aSeconds = aLastSec + (diff < 0 ? .3 : .1) * diff;
  274.       }
  275.  
  276.       // If the new time is similar, reuse something close to the last seconds,
  277.       // but subtract a little to provide forward progress
  278.       let diff = aSeconds - aLastSec;
  279.       let diffPct = diff / aLastSec * 100;
  280.       if (Math.abs(diff) < 5 || Math.abs(diffPct) < 5)
  281.         aSeconds = aLastSec - (diff < 0 ? .4 : .2);
  282.     }
  283.  
  284.     // Decide what text to show for the time
  285.     let timeLeft;
  286.     if (aSeconds < 4) {
  287.       // Be friendly in the last few seconds
  288.       timeLeft = gStr.timeFewSeconds;
  289.     } else {
  290.       // Convert the seconds into its two largest units to display
  291.       let [time1, unit1, time2, unit2] =
  292.         DownloadUtils.convertTimeUnits(aSeconds);
  293.  
  294.       let pair1 = replaceInsert(gStr.timePair, 1, time1);
  295.       pair1 = replaceInsert(pair1, 2, unit1);
  296.       let pair2 = replaceInsert(gStr.timePair, 1, time2);
  297.       pair2 = replaceInsert(pair2, 2, unit2);
  298.  
  299.       // Only show minutes for under 1 hour or the second pair is 0
  300.       if (aSeconds < 3600 || time2 == 0) {
  301.         timeLeft = replaceInsert(gStr.timeLeftSingle, 1, pair1);
  302.       } else {
  303.         // We've got 2 pairs of times to display
  304.         timeLeft = replaceInsert(gStr.timeLeftDouble, 1, pair1);
  305.         timeLeft = replaceInsert(timeLeft, 2, pair2);
  306.       }
  307.     }
  308.  
  309.     return [timeLeft, aSeconds];
  310.   },
  311.  
  312.   /**
  313.    * Get the appropriate display host string for a URI string depending on if
  314.    * the URI has an eTLD + 1, is an IP address, a local file, or other protocol
  315.    *
  316.    * @param aURIString
  317.    *        The URI string to try getting an eTLD + 1, etc.
  318.    * @return A pair: [display host for the URI string, full host name]
  319.    */
  320.   getURIHost: function DU_getURIHost(aURIString)
  321.   {
  322.     let ioService = Cc["@mozilla.org/network/io-service;1"].
  323.                     getService(Ci.nsIIOService);
  324.     let eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].
  325.                       getService(Ci.nsIEffectiveTLDService);
  326.     let idnService = Cc["@mozilla.org/network/idn-service;1"].
  327.                      getService(Ci.nsIIDNService);
  328.  
  329.     // Get a URI that knows about its components
  330.     let uri = ioService.newURI(aURIString, null, null);
  331.  
  332.     // Get the inner-most uri for schemes like jar:
  333.     if (uri instanceof Ci.nsINestedURI)
  334.       uri = uri.innermostURI;
  335.  
  336.     let fullHost;
  337.     try {
  338.       // Get the full host name; some special URIs fail (data: jar:)
  339.       fullHost = uri.host;
  340.     } catch (e) {
  341.       fullHost = "";
  342.     }
  343.  
  344.     let displayHost;
  345.     try {
  346.       // This might fail if it's an IP address or doesn't have more than 1 part
  347.       let baseDomain = eTLDService.getBaseDomain(uri);
  348.  
  349.       // Convert base domain for display; ignore the isAscii out param
  350.       displayHost = idnService.convertToDisplayIDN(baseDomain, {});
  351.     } catch (e) {
  352.       // Default to the host name
  353.       displayHost = fullHost;
  354.     }
  355.  
  356.     // Check if we need to show something else for the host
  357.     if (uri.scheme == "file") {
  358.       // Display special text for file protocol
  359.       displayHost = gStr.doneFileScheme;
  360.       fullHost = displayHost;
  361.     } else if (displayHost.length == 0) {
  362.       // Got nothing; show the scheme (data: about: moz-icon:)
  363.       displayHost = replaceInsert(gStr.doneScheme, 1, uri.scheme);
  364.       fullHost = displayHost;
  365.     } else if (uri.port != -1) {
  366.       // Tack on the port if it's not the default port
  367.       let port = ":" + uri.port;
  368.       displayHost += port;
  369.       fullHost += port;
  370.     }
  371.  
  372.     return [displayHost, fullHost];
  373.   },
  374.  
  375.   /**
  376.    * Converts a number of bytes to the appropriate unit that results in a
  377.    * number that needs fewer than 4 digits
  378.    *
  379.    * @param aBytes
  380.    *        Number of bytes to convert
  381.    * @return A pair: [new value with 3 sig. figs., its unit]
  382.    */
  383.   convertByteUnits: function DU_convertByteUnits(aBytes)
  384.   {
  385.     let unitIndex = 0;
  386.  
  387.     // Convert to next unit if it needs 4 digits (after rounding), but only if
  388.     // we know the name of the next unit
  389.     while ((aBytes >= 999.5) && (unitIndex < gStr.units.length - 1)) {
  390.       aBytes /= 1024;
  391.       unitIndex++;
  392.     }
  393.  
  394.     // Get rid of insignificant bits by truncating to 1 or 0 decimal points
  395.     // 0 -> 0; 1.2 -> 1.2; 12.3 -> 12.3; 123.4 -> 123; 234.5 -> 235
  396.     aBytes = aBytes.toFixed((aBytes > 0) && (aBytes < 100) ? 1 : 0);
  397.  
  398.     return [aBytes, gStr.units[unitIndex]];
  399.   },
  400.  
  401.   /**
  402.    * Converts a number of seconds to the two largest units. Time values are
  403.    * whole numbers, and units have the correct plural/singular form.
  404.    *
  405.    * @param aSecs
  406.    *        Seconds to convert into the appropriate 2 units
  407.    * @return 4-item array [first value, its unit, second value, its unit]
  408.    */
  409.   convertTimeUnits: function DU_convertTimeUnits(aSecs)
  410.   {
  411.     // These are the maximum values for seconds, minutes, hours corresponding
  412.     // with gStr.timeUnits without the last item
  413.     let timeSize = [60, 60, 24];
  414.  
  415.     let time = aSecs;
  416.     let scale = 1;
  417.     let unitIndex = 0;
  418.  
  419.     // Keep converting to the next unit while we have units left and the
  420.     // current one isn't the largest unit possible
  421.     while ((unitIndex < timeSize.length) && (time >= timeSize[unitIndex])) {
  422.       time /= timeSize[unitIndex];
  423.       scale *= timeSize[unitIndex];
  424.       unitIndex++;
  425.     }
  426.  
  427.     let value = convertTimeUnitsValue(time);
  428.     let units = convertTimeUnitsUnits(value, unitIndex);
  429.  
  430.     let extra = aSecs - value * scale;
  431.     let nextIndex = unitIndex - 1;
  432.  
  433.     // Convert the extra time to the next largest unit
  434.     for (let index = 0; index < nextIndex; index++)
  435.       extra /= timeSize[index];
  436.  
  437.     let value2 = convertTimeUnitsValue(extra);
  438.     let units2 = convertTimeUnitsUnits(value2, nextIndex);
  439.  
  440.     return [value, units, value2, units2];
  441.   },
  442. };
  443.  
  444. /**
  445.  * Private helper for convertTimeUnits that gets the display value of a time
  446.  *
  447.  * @param aTime
  448.  *        Time value for display
  449.  * @return An integer value for the time rounded down
  450.  */
  451. function convertTimeUnitsValue(aTime)
  452. {
  453.   return Math.floor(aTime);
  454. }
  455.  
  456. /**
  457.  * Private helper for convertTimeUnits that gets the display units of a time
  458.  *
  459.  * @param aTime
  460.  *        Time value for display
  461.  * @param aIndex
  462.  *        Index into gStr.timeUnits for the appropriate unit
  463.  * @return The appropriate plural form of the unit for the time
  464.  */
  465. function convertTimeUnitsUnits(aTime, aIndex)
  466. {
  467.   // Negative index would be an invalid unit, so just give empty
  468.   if (aIndex < 0)
  469.     return "";
  470.  
  471.   return PluralForm.get(aTime, gStr.timeUnits[aIndex]);
  472. }
  473.  
  474. /**
  475.  * Private helper function to replace a placeholder string with a real string
  476.  *
  477.  * @param aText
  478.  *        Source text containing placeholder (e.g., #1)
  479.  * @param aIndex
  480.  *        Index number of placeholder to replace
  481.  * @param aValue
  482.  *        New string to put in place of placeholder
  483.  * @return The string with placeholder replaced with the new string
  484.  */
  485. function replaceInsert(aText, aIndex, aValue)
  486. {
  487.   return aText.replace("#" + aIndex, aValue);
  488. }
  489.  
  490. /**
  491.  * Private helper function to log errors to the error console and command line
  492.  *
  493.  * @param aMsg
  494.  *        Error message to log or an array of strings to concat
  495.  */
  496. function log(aMsg)
  497. {
  498.   let msg = "DownloadUtils.jsm: " + (aMsg.join ? aMsg.join("") : aMsg);
  499.   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).
  500.     logStringMessage(msg);
  501.   dump(msg + "\n");
  502. }
  503.